//
//  InputViewController.m
//  Demo
//
//

#import "InputViewController.h"
#import "AppDownViewController.h"
#import "AboutViewController.h"
#import "NewWifiViewController.h"
#import "StudyViewController.h"
#import "QuestionViewController.h"
#import "TVViewController.h"
#import "PokerControlClient.h"
#import "NewDevice1ViewController.h"
#import "DeviceListViewController.h"
#import "DevSocketListViewController.h"
#import "RemoteControlClient.h"
#import "AsyncSocket.h"

@implementation InputViewController
@synthesize wifiReachability;
@synthesize udpSocket, phoneDic;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        downloadHelper = [[DownloadHelper alloc] initWithDelegate:self];
        listenSocket = [[AsyncSocket alloc] initWithDelegate:self];
        connectedSockets = [[NSMutableArray alloc] initWithCapacity:1];
        isRunning = NO;
        self.phoneDic = [NSMutableDictionary dictionary];
        m_port = 18003;
        [NC addObserver:self selector:@selector(connectWIFI) name:CONNECT_WIFI object:nil];
    }
    return self;
}
-(void)connectWIFI{
    isConnect = YES;
    [TableView1 reloadData];
}
-(void)dealloc{
    NSLog(@"");
    [NC removeObserver:self];
}
- (void)didFinishDownload:(id)result{
    
}
-(void)transfer{
    if (!shareBtn) {
        shareBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 200, kScreenWidth, kScreenHeight-64)];
        [shareBtn setImage:IMG(@"share_bg.png") forState:UIControlStateNormal];
        shareBtn.imageEdgeInsets = UIEdgeInsetsMake(shareBtn.frame.size.height-368/2, 2,  0, 2);
        [self.view addSubview:shareBtn];
        
        GoodLabel *shareLabel = [GoodLabel labelWithFont:16 title:STR(@"分享到")];
        shareLabel.textAlignment = NSTextAlignmentCenter;
        shareLabel.textColor = [UIColor blackColor];
        shareLabel.frame = CGRectMake(0, shareBtn.frame.size.height-160, shareBtn.frame.size.width, 20);
        [shareBtn addSubview:shareLabel];
        
        for (int i=0; i<3; i++) {
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(40+i*80, shareBtn.frame.size.height-120, 60, 55)];
            if (i == 0) {
                [btn setBackgroundImage:IMG(@"share_xl.png") forState:UIControlStateNormal];
            }else if (i == 1) {
                [btn setBackgroundImage:IMG(@"share_wx.png") forState:UIControlStateNormal];
            }else if (i == 2) {
                [btn setBackgroundImage:IMG(@"share_wxp.png") forState:UIControlStateNormal];
            }
            [btn addTarget:self action:@selector(shareBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
            [shareBtn addSubview:btn];
        }
        
        UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake((shareBtn.frame.size.width-197)/2, shareBtn.frame.size.height-40, 197, 24)];
        cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [cancelBtn setTitle:STR(@"取消") forState:UIControlStateNormal];
        if ([Global curLanguageEn]) {
            [cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];
        }
        [cancelBtn setBackgroundImage:IMG(@"APP_link_btn.png") forState:UIControlStateNormal];
        [cancelBtn addTarget:self action:@selector(cancelBtnPressed) forControlEvents:UIControlEventTouchUpInside];
        [shareBtn addSubview:cancelBtn];
        
        [UIView animateWithDuration:.3 animations:^{
            shareBtn.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
        } completion:^(BOOL finished) {
            
        }];
    }
}
-(void)shareBtnPressed:(UIButton*)btn{
    [shareBtn removeFromSuperview]; shareBtn = nil;
}
-(void)cancelBtnPressed{
    [shareBtn removeFromSuperview]; shareBtn = nil;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    if (netStatus != NotReachable ) {// No activity if no wifi
    
//    NSMutableDictionary *dicList = [UD objectForKey:LANIPAddress_list];
//    if (dicList.count >= 1) {
//        NSString *IPADDR = [[dicList allValues] objectAtIndex:0];
//        NSLog(@"给ip地址赋值: %@", IPADDR);
//        [PokerControlClient share].ctrlIP = IPADDR;
//        [[PokerControlClient share] performSelector:@selector(c2sPing) withObject:nil afterDelay:2];
//    }
    
//    }
}
- (void)viewDidLoad
{
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//    [dic setObject:@"192.168.1.105" forKey:@"R0026290305a2"];
//    [dic setObject:@"192.168.1.106" forKey:@"R0026290305a3"];
//    [dic setObject:@"192.168.1.107" forKey:@"R002629030502"];
//    [dic setObject:@"192.168.1.108" forKey:@"R002629030806"];
//    [dic setObject:@"192.168.1.109" forKey:@"002629030800"];
//    [UD setObject:dic forKey:LANIPAddress_list];
//    [UD synchronize];
//
//    
//    [self getXmlStr];//for test
    
    
    self.title = STR(@"Wi-Fi智能家居系列");
    if ([Global curLanguageEn]) {
        self.title = @"Wi-Fi smart home series";
    }
    [super viewDidLoad];
    
    [NC addObserver:self selector:@selector(exportFinished) name:NOTI_EXPORT_FINISHED object:nil];
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
//    self.navigationItem.backBarButtonItem = nil;
    
    [PokerControlClient share];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wifiStatusChanged:) name:kReachabilityChangedNotification object:nil];
    
    self.wifiReachability = [Reachability reachabilityForLocalWiFi];
    [self.wifiReachability connectionRequired];
	[self.wifiReachability startNotifier];
    
    netStatus = [wifiReachability currentReachabilityStatus];
    if ( netStatus == NotReachable ) {// No activity if no wifi
        NSLog(@"WiFi not available");
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"CC3x Alert" message:@"WiFi not available. Please check your WiFi connection" delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
//        [alertView show];
    }else{
        
    }
    
//    rightItem = [UIBarButtonItem backImageBarButtonItem:[UIImage imageNamed:@"transfer.png"] target:self action:@selector(transfer)];
//    self.navigationItem.rightBarButtonItem = rightItem;
    
    TableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-45-44-20) style:UITableViewStylePlain];
    TableView1.backgroundColor = [UIColor clearColor];
    TableView1.delegate = self;
    TableView1.dataSource = self;
    TableView1.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:TableView1];
    
    TableView2 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-45-44-20) style:UITableViewStylePlain];
    TableView2.backgroundColor = [UIColor clearColor];
    TableView2.delegate = self;
    TableView2.dataSource = self;
    TableView2.hidden = YES;
    TableView2.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:TableView2];
    
    for (int i=0; i<2; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(i*(kScreenWidth/2), kScreenHeight-45-44-20, kScreenWidth/2, 45)];
        
        GoodLabel *descLabel = [GoodLabel labelWithFont:9 title:STR(@"红外")];
        if ([Global curLanguageEn]) {
            descLabel.text = @"Remote";
        }
        descLabel.hidden = YES;
        descLabel.textAlignment = NSTextAlignmentCenter;
        descLabel.frame = CGRectMake(0, 30, btn.frame.size.width, 16);
        [btn addSubview:descLabel];
        int top = 6;
        int width = 36;
        if (i == 0) {
            int left = (btn.frame.size.width-width)/2;
            btn.imageEdgeInsets = UIEdgeInsetsMake(top,  (btn.frame.size.width-28)/2,  top, left);
            btn.enabled = NO;
            btn1 = btn;
            [btn setImage:IMG(@"more_select.png") forState:UIControlStateNormal];
            [btn setImage:IMG(@"more.png") forState:UIControlStateDisabled];
        }else{
            int left = (btn.frame.size.width-width-2)/2;
            btn.imageEdgeInsets = UIEdgeInsetsMake(top+2, left,  top+2, left);
            descLabel.text = STR(@"更多");
            if ([Global curLanguageEn]) {
                descLabel.text = @"More";
            }
            btn2 = btn;
            [btn setImage:IMG(@"control_select.png") forState:UIControlStateNormal];
            [btn setImage:IMG(@"control.png") forState:UIControlStateDisabled];
        }
        btn.tag = i;
        [btn setBackgroundImage:IMG(@"TabBarBtn.png") forState:UIControlStateNormal];
        [btn setBackgroundImage:IMG(@"TabBarBtn_selected.png") forState:UIControlStateDisabled];
        [btn addTarget:self action:@selector(buttombBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        
        
    }
    
//    TVViewController *studyView = [[TVViewController alloc] init];
//    [self.navigationController pushViewController:studyView animated:YES];
    // Do any additional setup after loading the view from its nib.
}
/*
 Notification method handler when status of wifi changes
 @param the fired notification object
 */
- (void)wifiStatusChanged:(NSNotification*)notification{
    NSLog(@"%s", __func__);
    Reachability *verifyConnection = [notification object];
    NSAssert(verifyConnection != NULL, @"currentNetworkStatus called with NULL verifyConnection Object");
    netStatus = [verifyConnection currentReachabilityStatus];
    if ( netStatus == NotReachable ){
        NSLog(@"wifiStatusChanged Wifi Not available");
        // The operation couldn’t be completed. No route to host
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"CC3x Alert" message:@"Wifi Not available. Please check your wifi connection" delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
//        [alertView show];

    }else {
        
    }
}
-(void)buttombBtnPressed:(UIButton*)btn{
    btn1.enabled = YES; btn2.enabled = YES;
    if (btn.tag == 0) {
        btn1.enabled = NO;
        self.title = STR(@"智能遥控列表");
        if ([Global curLanguageEn]) {
            self.title = @"Smart IR Controller List";
        }
        rightItem.customView.hidden = NO;
        TableView1.hidden = NO;
        TableView2.hidden = YES;
    }else{
        btn2.enabled = NO;
        self.title = STR(@"更多功能");
        if ([Global curLanguageEn]) {
            self.title = @"More";
        }
        rightItem.customView.hidden = YES;
        TableView1.hidden = YES;
        TableView2.hidden = NO;
    }
    /*InputViewController *input = [[InputViewController alloc] initWithNibName:@"InputViewController" bundle:nil];
    UINavigationController *navi = [[[UINavigationController alloc] initWithRootViewController:input] autorelease];
    [self presentModalViewController:navi animated:YES];*/
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == TableView1) {
        return 6;
    }
//    return 5;
    return 7;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == TableView1) {
        static NSString *CellIdentifier = @"TableView1Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 62)];
//        bg.image = IMG(@"cell_bg.png");
        bg.backgroundColor = [UIColor whiteColor];
        [cell addSubview:bg];
        
        UIImageView *logo = [[UIImageView alloc] initWithImage:IMG(@"control_logo.png")];
        logo.frame = CGRectMake(1.5+8, 9.5, 66-8*2, 43);
        [cell addSubview:logo];
        
        GoodLabel *nameLabel = [GoodLabel labelWithFont:14 title:STR(@"")];
//        nameLabel.textAlignment = UITextAlignmentCenter;
        if (indexPath.row == 0) {
            nameLabel.text = STR(@"Wi-Fi智能红外遥控器");
            if ([Global curLanguageEn]) {
                nameLabel.text = @"Smart IR Control";
            }
        }else if (indexPath.row == 1) {
            logo.image = IMG(@"icon_socket.png");
            logo.frame = CGRectMake(1.5+8+8, 6, 55/1.8, 84/1.8);
            nameLabel.text = STR(@"Wi-Fi智能插座");
            if ([Global curLanguageEn]) {
                nameLabel.text = @"Smart Socket";
            }
        }else if (indexPath.row == 2) {
            logo.image = IMG(@"icon_touch_switch.png");
            logo.frame = CGRectMake(1.5+8, 9.5, 44, 43);
            nameLabel.text = STR(@"Wi-Fi智能触摸开关");
            if ([Global curLanguageEn]) {
                nameLabel.text = @"Smart Switch";
            }
        }else if (indexPath.row == 3) {
            logo.image = IMG(@"icon_led.png");
            logo.frame = CGRectMake(1.5+8, 9.5, 43, 44);
            nameLabel.text = STR(@"Wi-Fi智能LED");
            if ([Global curLanguageEn]) {
                nameLabel.text = @"Smart LED";
            }
        }else if (indexPath.row == 4) {
            logo.image = IMG(@"icon_air_detector.png");
            logo.frame = CGRectMake(1.5+8, 9.5, 43, 44);
            nameLabel.text = STR(@"Wi-Fi智能环境监测仪");
            if ([Global curLanguageEn]) {
                nameLabel.text = @"Smart Air Detector";
            }
        }else if (indexPath.row == 5) {
            logo.image = IMG(@"icon_smart_controller.png");
            logo.frame = CGRectMake(1.5+8, 9.5, 43, 44);
            nameLabel.text = STR(@"Wi-Fi智能控制器");
            if ([Global curLanguageEn]) {
                nameLabel.text = @"Smart Control";
            }
        }
        nameLabel.textColor = [UIColor blackColor];
        nameLabel.frame = CGRectMake(85, 10+11, kScreenWidth/2, 20);
        [cell addSubview:nameLabel];
        
//        if ([UD objectForKey:DEVICE_NAME]) {
//            GoodLabel *deviceLabel = [GoodLabel labelWithFont:12 title:[UD objectForKey:DEVICE_NAME]];
//            deviceLabel.textAlignment = UITextAlignmentCenter;
//            deviceLabel.textColor = [UIColor blackColor];
//            deviceLabel.frame = CGRectMake(FX(nameLabel), 30+5, kScreenWidth/2, 20);
//            [cell addSubview:deviceLabel];
//        }
        
        UIImage *stateImage = IMG(@"offline.png");
        if ([Global curLanguageEn]) {
            stateImage = IMG(@"offline_en.png");
        }
        if (indexPath.row == 0) {
            if (isConnect) {
                stateImage = IMG(@"share.png");
            }
        }
        stateImage = IMG(@"share.png");
        UIImageView *state = [[UIImageView alloc] initWithImage:stateImage];
        state.frame = CGRectMake(kScreenWidth-stateImage.size.width/2-5, (62-stateImage.size.height/2)/2, stateImage.size.width/2, stateImage.size.height/2);
        [cell addSubview:state];
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }else{
        static NSString *CellIdentifier = @"TableView2Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 62)];
        bg.backgroundColor = [UIColor whiteColor];
//        bg.image = IMG(@"cell_bg.png");
        [cell addSubview:bg];
        NSString *name = [NSString stringWithFormat:@"more_logo_%d", indexPath.row];
        UIImage *image = IMG(name);
        if (image) {
            UIImageView *logo = [[UIImageView alloc] initWithImage:image];
            logo.frame = CGRectMake((62-image.size.height/2)/2, (62-image.size.height/2)/2, image.size.width/2, image.size.height/2);
            [cell addSubview:logo];
        }
        GoodLabel *descLabel = [GoodLabel labelWithFont:16 title:STR(@"添加新设备")];
        if ([Global curLanguageEn]) {
            descLabel.text = @"Add New Device";
        }
        descLabel.textColor = [UIColor blackColor];
        descLabel.frame = CGRectMake(75, 42/2, kScreenWidth/2, 20);
        [cell addSubview:descLabel];
        
        
        if (indexPath.row == 1) {
            descLabel.text = @"数据导出";
            if ([Global curLanguageEn]) {
                descLabel.text = @"Export";
            }
        }else if (indexPath.row == 2) {
            descLabel.text = @"数据导入";
            if ([Global curLanguageEn]) {
                descLabel.text = @"Import";
            }
        }else
            if (indexPath.row == 3) {
            descLabel.text = STR(@"按键震动");
                if ([Global curLanguageEn]) {
                    descLabel.text = @"Vibrate";
                }
            UISwitch *switchBtn = [[UISwitch alloc] init];
            cell.accessoryView = switchBtn;
            if ([[NSUserDefaults standardUserDefaults] boolForKey:ENABLE_VIBRATE_KEY]) {
                [switchBtn setOn:YES];
            }else{
                [switchBtn setOn:NO];
            }
            [switchBtn addTarget:self action:@selector(onSwitchValueChanged:) forControlEvents:UIControlEventValueChanged];
        }else if (indexPath.row == 2+2) {
            descLabel.text = STR(@"APP下载链接");
            if ([Global curLanguageEn]) {
                descLabel.text = @"APP Download Link";
            }
        }else if (indexPath.row == 3+2) {
            descLabel.text = STR(@"常见问题");
            if ([Global curLanguageEn]) {
                descLabel.text = @"FAQ";
            }
        }else if (indexPath.row == 4+2) {
            descLabel.text = STR(@"关于我们");
#ifndef HAIDIAN_VERSION
            descLabel.text = STR(@"关于海电科技");
#endif
            if ([Global curLanguageEn]) {
                descLabel.text = @"About US";
            }
        }
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
}
-(IBAction)onSwitchValueChanged:(UISwitch*)sender{
    [[NSUserDefaults standardUserDefaults] setBool:sender.on forKey:ENABLE_VIBRATE_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if (sender.on) {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == TableView1){
        if (indexPath.row == 0) {
            DeviceListViewController *view = [[DeviceListViewController alloc] init];
            [self.navigationController pushViewController:view animated:YES];
        }
        else if (indexPath.row == 1){
            DevSocketListViewController *view = [[DevSocketListViewController alloc] init];
            [self.navigationController pushViewController:view animated:YES];
        }
        
    }else if (tableView == TableView2){
        if (indexPath.row == 0) {
            NewDeviceViewController *newDeviceView = [[NewDeviceViewController alloc] init];
            [self.navigationController pushViewController:newDeviceView animated:YES];
        }else if (indexPath.row == 1) {//导出
            isDataImport = NO;
            isStopUdpSend = NO;
            if ([Global curLanguageEn]) {
                m_sheet = [[UIAlertView alloc] initWithTitle:@"" message:@"Export..." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                [m_sheet show];
            }else{
                m_sheet = [[UIAlertView alloc] initWithTitle:@"" message:STR(@"数据导出中...") delegate:self cancelButtonTitle:STR(@"取消") otherButtonTitles:nil, nil];
                [m_sheet show];
            }
            [self sendUdpData];
        }else if (indexPath.row == 2) {//导入
            isDataImport = YES;
            [PokerControlClient share];
            isStopUdpSend = NO;
            if ([Global curLanguageEn]) {
                m_sheet = [[UIAlertView alloc] initWithTitle:@"" message:@"Import..." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                [m_sheet show];
            }else{
                m_sheet = [[UIAlertView alloc] initWithTitle:@"" message:STR(@"数据导入中...") delegate:self cancelButtonTitle:STR(@"取消") otherButtonTitles:nil, nil];
                [m_sheet show];
            }
            m_sheet.tag = 2;
            
            if (!self.udpSocket) {
                self.udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
            }
            NSError *error = nil;
            if (![udpSocket bindToPort:m_port error:&error])
            {
                NSLog(@"Error starting server (bind): %@", error);
                return;
            }
            [udpSocket receiveWithTimeout:-1 tag:0];
            NSLog(@"Udp Echo server started on port %hu", [udpSocket localPort]);
        }else if (indexPath.row == 2+2) {
            AppDownViewController *downView = [[AppDownViewController alloc] init];
            [self.navigationController pushViewController:downView animated:YES];
        }else if (indexPath.row == 3+2) {
            QuestionViewController *questionView = [[QuestionViewController alloc] init];
            [self.navigationController pushViewController:questionView animated:YES];
        }else if (indexPath.row == 4+2) {
            AboutViewController *aboutView = [[AboutViewController alloc] init];
            [self.navigationController pushViewController:aboutView animated:YES];
        }
    }else{
        
    }
}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
     didReceiveData:(NSData *)data
            withTag:(long)tag
           fromHost:(NSString *)host
               port:(UInt16)port
{
	NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	if (msg){
        if (isDataImport && !isSend && [[PokerControlClient share].ctrlPort intValue]==import_port) {
            [self.udpSocket close];
            self.udpSocket = nil;
            [[PokerControlClient share] openImportStream];
            isSend = YES;
        }
        [self.phoneDic setObject:@"phone" forKey:msg];
        NSLog(@"msg : %@", msg);
	}else
	{
        NSLog(@"Error converting received data into UTF-8 String");
	}
//	[udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0];
//	[udpSocket receiveWithTimeout:-1 tag:0];
	return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    isSend = NO;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendUdpData) object:nil];
    [self.udpSocket close];
    self.udpSocket = nil;
    isStopUdpSend = YES;
    if (alertView.tag == 2) {
        
    }
}
-(void)exportFinished{
    [m_sheet dismissWithClickedButtonIndex:0 animated:YES];
    if ([Global curLanguageEn]) {
        UIAlertView *alertTemp = [[UIAlertView alloc] initWithTitle:@"" message:@"Successful Import" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertTemp show];
    }else{
        UIAlertView *alertTemp = [[UIAlertView alloc] initWithTitle:@"" message:STR(@"成功导入") delegate:nil cancelButtonTitle:nil otherButtonTitles:STR(@"确定"), nil];
        [alertTemp show];
    }
}
-(void)startServer{
    if (!isRunning) {
        int port = 18004;
        NSError *error = nil;
        if(![listenSocket acceptOnPort:port error:&error])
        {
            NSLog(@"Error starting server: %@", error);
            return;
        }
        NSLog(@"Echo server started on port %hu", [listenSocket localPort]);
        isRunning = YES;
    }else
	{
		// Stop accepting connections
		[listenSocket disconnect];
        
		// Stop any client connections
		NSUInteger i;
		for(i = 0; i < [connectedSockets count]; i++)
		{
			// Call disconnect on the socket,
			// which will invoke the onSocketDidDisconnect: method,
			// which will remove the socket from the list.
			[[connectedSockets objectAtIndex:i] disconnect];
		}
		NSLog(@"Stopped Echo server");
		isRunning = false;
	}
}

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
	[connectedSockets addObject:newSocket];
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
	NSLog(@"Accepted client %@:%hu", host, port);
	[sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
	[sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
	NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
	NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
	if(msg)
	{
        NSLog(@"recv msg: %@", msg);
	}
	else
	{
        NSLog(@"Error converting received data into UTF-8 String");
	}
    if ([msg hasPrefix:@"<data><cmd>1001</cmd>"]) {
        NSString *xmlStr = [self getXmlStr];
        //	NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n";
        //	NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"send data : %@", xmlStr);
        [sock writeData:[xmlStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:30 tag:0];
    }
}
-(NSString *)getXmlStr{
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSMutableArray *replaceArray = [[NSMutableArray alloc] init];
    
    NSString *tag = @"qwertyuiopasd";
    int index = 1;
    
    
    DDXMLElement *dataElement = [DDXMLElement elementWithName:@"data"];
    [dataElement addChildWithName:@"cmd" stringValue:@"1001"];
    DDXMLElement *deviceElement = [DDXMLElement elementWithName:@"device"];
    DDXMLElement *remoteElement = [DDXMLElement elementWithName:@"remote"];
    DDXMLElement *keyElement = [DDXMLElement elementWithName:@"key"];
    NSDictionary *remote_device_list = [UD objectForKey:LANIPAddress_list];
    for (NSString* deviceid in [remote_device_list allKeys]) {
        DDXMLElement *device_itemElement = [DDXMLElement elementWithName:@"device_item"];
        [deviceElement addChild:device_itemElement];
        [device_itemElement addAttributeWithName:@"id" stringValue:deviceid];
        [device_itemElement addAttributeWithName:@"icon" stringValue:@""];
        [device_itemElement addAttributeWithName:@"type" stringValue:@"remote"];
        [device_itemElement addAttributeWithName:@"name" stringValue:[NSString stringWithFormat:@"%@%d", tag, ++index]];
        
        [array addObject:[NSString stringWithFormat:@"%@%d", tag, index]];
        [replaceArray addObject:@"Wi-Fi智能红外遥控器"];
        
        int remote_id = 1;
        for (DeviceInfo *deviceInfo in [[DataManager GetInstance:deviceid] getWithName:deviceid]) {
            DDXMLElement *remote_itemElement = [DDXMLElement elementWithName:@"remote_item"];
            [remoteElement addChild:remote_itemElement];
            NSString *str_remote_id = [NSString stringWithFormat:@"id_%d", remote_id];
            [remote_itemElement addAttributeWithName:@"device_id" stringValue:deviceid];
            [remote_itemElement addAttributeWithName:@"remote_id" stringValue:str_remote_id];
            [remote_itemElement addAttributeWithName:@"name" stringValue:[NSString stringWithFormat:@"%@%d", tag, ++index]];
            
            [array addObject:[NSString stringWithFormat:@"%@%d", tag, index]];
            [replaceArray addObject:deviceInfo.name];
            
            [remote_itemElement addAttributeWithName:@"type" stringValue:[self enumToString:deviceInfo.type]];
            [remote_itemElement addAttributeWithName:@"icon" stringValue:[self typeToIcon:deviceInfo.type]];
            [remote_itemElement addAttributeWithName:@"position" stringValue:[NSString stringWithFormat:@"%d", remote_id-1]];
            int tag_num = 0;
            for (NSDataInfo *dataInfo in deviceInfo.keyArray) {
                if (dataInfo.isStudy) {
                    DDXMLElement *key_itemElement = [DDXMLElement elementWithName:@"key_item"];
                    [keyElement addChild:key_itemElement];
                    [key_itemElement addAttributeWithName:@"device_id" stringValue:deviceid];
                    [key_itemElement addAttributeWithName:@"remote_id" stringValue:str_remote_id];
                    
                    if (dataInfo.temp) {
                       [key_itemElement addAttributeWithName:@"name" stringValue:[NSString stringWithFormat:@"%@%d", tag, ++index]];
                        
                        
                        [array addObject:[NSString stringWithFormat:@"%@%d", tag, index]];
                        [replaceArray addObject:dataInfo.temp];
                        
                    }else if (dataInfo.btnName) {
                        [key_itemElement addAttributeWithName:@"name" stringValue:[NSString stringWithFormat:@"%@%d", tag, ++index]];
                        
                        [array addObject:[NSString stringWithFormat:@"%@%d", tag, index]];
                        [replaceArray addObject:dataInfo.btnName];
                    }
                    
                    if (dataInfo.isCustom) {//自定义
                        [key_itemElement addAttributeWithName:@"icon" stringValue:[self iphoneIconToAndroidIcon:dataInfo.name]];
                        [key_itemElement addAttributeWithName:@"tag" stringValue:dataInfo._id];
                        [key_itemElement addAttributeWithName:@"screen_width" stringValue:[NSString stringWithFormat:@"%f", SCREEN_WIDTH]];
                        [key_itemElement addAttributeWithName:@"screen_height" stringValue:[NSString stringWithFormat:@"%f", SCREEN_HEIGHT]];
                        [key_itemElement addAttributeWithName:@"x" stringValue:[NSString stringWithFormat:@"%d", dataInfo.frame_x]];
                        [key_itemElement addAttributeWithName:@"y" stringValue:[NSString stringWithFormat:@"%d", dataInfo.frame_y]];
                    }else{
                        [key_itemElement addAttributeWithName:@"icon" stringValue:@"null"];
                        [key_itemElement addAttributeWithName:@"tag" stringValue:[self iPhoneTagToAndroidTag:tag_num deviceType:deviceInfo.type]];
                        [key_itemElement addAttributeWithName:@"screen_width" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"screen_height" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"x" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"y" stringValue:@"0"];
                    }
                    if (dataInfo.array.count > 0) {
                        [key_itemElement addAttributeWithName:@"is_combination_key" stringValue:@"1"];
                        int num = 0;
                        for (DelayInfo *delayInfo in dataInfo.array) {
                            if (num == 0) {
                                [key_itemElement addAttributeWithName:@"keycode1" stringValue:delayInfo.app_cmd];
                                [key_itemElement addAttributeWithName:@"delay1" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
                            }else if (num == 1) {
                                [key_itemElement addAttributeWithName:@"keycode2" stringValue:delayInfo.app_cmd];
                                [key_itemElement addAttributeWithName:@"delay2" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
                            }else if (num == 2) {
                                [key_itemElement addAttributeWithName:@"keycode3" stringValue:delayInfo.app_cmd];
                                [key_itemElement addAttributeWithName:@"delay3" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
                            }else if (num == 3) {
                                [key_itemElement addAttributeWithName:@"keycode4" stringValue:delayInfo.app_cmd];
                                [key_itemElement addAttributeWithName:@"delay4" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
                            }else if (num == 4) {
                                [key_itemElement addAttributeWithName:@"keycode5" stringValue:delayInfo.app_cmd];
                                [key_itemElement addAttributeWithName:@"delay5" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
                            }else if (num == 5) {
                                [key_itemElement addAttributeWithName:@"keycode6" stringValue:delayInfo.app_cmd];
                            }
                            num++;
                        }
                    }else{
                        [key_itemElement addAttributeWithName:@"is_combination_key" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"keycode1" stringValue:dataInfo.app_cmd];
                        [key_itemElement addAttributeWithName:@"delay1" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"keycode2" stringValue:@""];
                        [key_itemElement addAttributeWithName:@"delay2" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"keycode3" stringValue:@""];
                        [key_itemElement addAttributeWithName:@"delay3" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"keycode4" stringValue:@""];
                        [key_itemElement addAttributeWithName:@"delay4" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"keycode5" stringValue:@""];
                        [key_itemElement addAttributeWithName:@"delay5" stringValue:@"0"];
                        [key_itemElement addAttributeWithName:@"keycode6" stringValue:@""];
                    }
                }else if(!dataInfo.isStudy && dataInfo.isCustom){
                    DDXMLElement *key_itemElement = [DDXMLElement elementWithName:@"key_item"];
                    [keyElement addChild:key_itemElement];
                    [key_itemElement addAttributeWithName:@"device_id" stringValue:deviceid];
                    [key_itemElement addAttributeWithName:@"remote_id" stringValue:str_remote_id];
                    
                    if (dataInfo.temp) {
                        [key_itemElement addAttributeWithName:@"name" stringValue:[NSString stringWithFormat:@"%@%d", tag, ++index]];
                        
                        [array addObject:[NSString stringWithFormat:@"%@%d", tag, index]];
                        [replaceArray addObject:dataInfo.temp];
                        
                    }else if (dataInfo.btnName) {
                        [key_itemElement addAttributeWithName:@"name" stringValue:[NSString stringWithFormat:@"%@%d", tag, ++index]];
                        
                        [array addObject:[NSString stringWithFormat:@"%@%d", tag, index]];
                        [replaceArray addObject:dataInfo.btnName];
                    }
                    [key_itemElement addAttributeWithName:@"icon" stringValue:[self iphoneIconToAndroidIcon:dataInfo.name]];
                    [key_itemElement addAttributeWithName:@"tag" stringValue:dataInfo._id];
                    [key_itemElement addAttributeWithName:@"screen_width" stringValue:[NSString stringWithFormat:@"%f", SCREEN_WIDTH]];
                    [key_itemElement addAttributeWithName:@"screen_height" stringValue:[NSString stringWithFormat:@"%f", SCREEN_HEIGHT]];
                    [key_itemElement addAttributeWithName:@"x" stringValue:[NSString stringWithFormat:@"%d", dataInfo.frame_x]];
                    [key_itemElement addAttributeWithName:@"y" stringValue:[NSString stringWithFormat:@"%d", dataInfo.frame_y]];
                    
//                    if (dataInfo.array.count > 0) {
//                        [key_itemElement addAttributeWithName:@"is_combination_key" stringValue:@"1"];
//                        int num = 0;
//                        for (DelayInfo *delayInfo in dataInfo.array) {
//                            if (num == 0) {
//                                [key_itemElement addAttributeWithName:@"keycode1" stringValue:delayInfo.app_cmd];
//                                [key_itemElement addAttributeWithName:@"delay1" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
//                            }else if (num == 1) {
//                                [key_itemElement addAttributeWithName:@"keycode2" stringValue:delayInfo.app_cmd];
//                                [key_itemElement addAttributeWithName:@"delay2" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
//                            }else if (num == 2) {
//                                [key_itemElement addAttributeWithName:@"keycode3" stringValue:delayInfo.app_cmd];
//                                [key_itemElement addAttributeWithName:@"delay3" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
//                            }else if (num == 3) {
//                                [key_itemElement addAttributeWithName:@"keycode4" stringValue:delayInfo.app_cmd];
//                                [key_itemElement addAttributeWithName:@"delay4" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
//                            }else if (num == 4) {
//                                [key_itemElement addAttributeWithName:@"keycode5" stringValue:delayInfo.app_cmd];
//                                [key_itemElement addAttributeWithName:@"delay5" stringValue:[NSString stringWithFormat:@"%@", delayInfo.time]];
//                            }else if (num == 5) {
//                                [key_itemElement addAttributeWithName:@"keycode6" stringValue:delayInfo.app_cmd];
//                            }
//                            num++;
//                        }
//                    }else{
//                        [key_itemElement addAttributeWithName:@"is_combination_key" stringValue:@"0"];
//                        [key_itemElement addAttributeWithName:@"keycode1" stringValue:dataInfo.app_cmd];
//                        [key_itemElement addAttributeWithName:@"delay1" stringValue:@"0"];
//                        [key_itemElement addAttributeWithName:@"keycode2" stringValue:@""];
//                        [key_itemElement addAttributeWithName:@"delay2" stringValue:@"0"];
//                        [key_itemElement addAttributeWithName:@"keycode3" stringValue:@""];
//                        [key_itemElement addAttributeWithName:@"delay3" stringValue:@"0"];
//                        [key_itemElement addAttributeWithName:@"keycode4" stringValue:@""];
//                        [key_itemElement addAttributeWithName:@"delay4" stringValue:@"0"];
//                        [key_itemElement addAttributeWithName:@"keycode5" stringValue:@""];
//                        [key_itemElement addAttributeWithName:@"delay5" stringValue:@"0"];
//                        [key_itemElement addAttributeWithName:@"keycode6" stringValue:@""];
//                    }
                }
                tag_num++;
            }
            remote_id++;
        }
    }
    NSDictionary *socket_device_list = [UD objectForKey:LAN_SOCKET_IPAddress_list];
    for (NSString* deviceid in [socket_device_list allKeys]) {
        DDXMLElement *device_itemElement = [DDXMLElement elementWithName:@"device_item"];
        [deviceElement addChild:device_itemElement];
        [device_itemElement addAttributeWithName:@"id" stringValue:deviceid];
        [device_itemElement addAttributeWithName:@"icon" stringValue:@""];
        [device_itemElement addAttributeWithName:@"type" stringValue:@"socket"];
        [device_itemElement addAttributeWithName:@"name" stringValue:[NSString stringWithFormat:@"%@%d", tag, ++index]];
        
        [array addObject:[NSString stringWithFormat:@"%@%d", tag, index]];
        [replaceArray addObject:@"WI-FI智能插座"];
        
    }
    DDXMLElement *fileElement = [DDXMLElement elementWithName:@"file"];
    [dataElement addChild:deviceElement];
    [dataElement addChild:remoteElement];
    [dataElement addChild:keyElement];
    [dataElement addChild:fileElement];
    NSString *xmlStr = [dataElement compactXMLString];
    
    
    for (int i=0; i<array.count; i++) {
        NSString *string = [array objectAtIndex:i];
        NSString *stringReplace = [replaceArray objectAtIndex:i];
        xmlStr = [xmlStr stringByReplacingOccurrencesOfString:string withString:stringReplace];
    }
    NSLog(@"数据导出 : %@", xmlStr);
    return xmlStr;
}
-(NSString*)iphoneIconToAndroidIcon:(NSString*)icon{
    NSString *iPhoneIcon = nil;
    if ([icon hasSuffix:@"custom_left"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/custom_left_unstudy";
    }else if ([icon hasSuffix:@"custom_right"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/custom_right_unstudy";
    }else if ([icon hasSuffix:@"custom_up"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/custom_up_unstudy";
    }else if ([icon hasSuffix:@"custom_down"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/custom_down_unstudy";
    }
    else if ([icon hasSuffix:@"custom_ok"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/ok_unstudy";
    }else if ([icon hasSuffix:@"open"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/power_unstudy";
    }else if ([icon hasSuffix:@"custom_plus"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/custom_add_unstudy";
    }else if ([icon hasSuffix:@"custom_reduce"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/custom_rd_unstudy";
    }
    else if ([icon hasSuffix:@"custom_volume_large"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/custom_vadd_unstudy";
    }else if ([icon hasSuffix:@"custom_volume_small"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/custom_vrd_unstudy";
    }else if ([icon hasSuffix:@"custom_off"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/power_off_unstudy";
    }else if ([icon hasSuffix:@"custom_on"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/power_on_unstudy";
    }
//    else if ([icon hasSuffix:@"custom_button"]) {
//        iPhoneIcon = @"com.haidian.remote:drawable/custom_button_2";
//    }
    else if ([icon hasSuffix:@"tv_home_button"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/home_unstudy";
    }else if ([icon hasSuffix:@"com.haidian.remote:drawable/mute_unstudy"]) {
        iPhoneIcon = @"mute_unstudy";
    }else if ([icon hasSuffix:@"back_button"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/back_unstudy";
    }else if ([icon hasSuffix:@"AV_button"]) {
        iPhoneIcon = @"com.haidian.remote:drawable/av_tv_unstudy";
    }
    return iPhoneIcon;
}
-(NSString*)iPhoneTagToAndroidTag:(NSInteger)tag deviceType:(DEVICE_TYPE)deviceType{
    NSString *androidTag = nil;
    if (deviceType == DEVICE_AIR) {
        if (tag == 0) {
            androidTag = @"01";
        }else if (tag == 1) {
            androidTag = @"06";
        }else if (tag == 2) {
            androidTag = [NSString stringWithFormat:@"%02d", tag];
        }else if (tag == 3) {
            androidTag = [NSString stringWithFormat:@"%02d", tag];
        }else if (tag == 5) {
            androidTag = @"04";
        }
    }else if (deviceType==DEVICE_TV || deviceType==DEVICE_STB) {//中间五个+右边2个
        if (tag == 8) {
            androidTag = @"05";
        }else if (tag == 9) {
            androidTag = @"06";
        }else if (tag == 6) {
            androidTag = @"07";
        }else if (tag == 7) {
            androidTag = @"08";
        }else if (tag == 10) {
            androidTag = @"09";
        }else if (tag == 4) {
            androidTag = @"10";
        }else if (tag == 5) {
            androidTag = @"11";
        }else {
            androidTag = [NSString stringWithFormat:@"%02d", tag+1];
        }
    }else if (deviceType == DEVICE_SOUND) {//中间五个不一样
        if (tag == 4) {
            androidTag = @"03";
        }else if (tag == 5) {
            androidTag = @"04";
        }else if (tag == 2) {
            androidTag = @"05";
        }else if (tag == 3) {
            androidTag = @"06";
        }else if (tag == 6) {
            androidTag = @"07";
        }else {
            androidTag = [NSString stringWithFormat:@"%02d", tag+1];
        }
    }else if (deviceType == DEVICE_SOCKET3) {
        if (tag == 1) {
            androidTag = @"04";
        }else if (tag == 2) {
            androidTag = @"02";
        }else if (tag == 3) {
            androidTag = @"03";
        }else if (tag == 0) {
            androidTag = @"01";
        }
    }else if (deviceType==DEVICE_SOCKET2 || deviceType==DEVICE_SOCKET1) {
        androidTag = [NSString stringWithFormat:@"%02d", tag+1];
    }
    return androidTag;
}
-(NSString*)typeToIcon:(DEVICE_TYPE)type{
    NSString *deviceIcon = nil;
    if (type == DEVICE_TV) {//电视
        deviceIcon = @"com.haidian.remote:drawable/icon_template_tv";
    }else if (type == DEVICE_AIR) {//空调
        deviceIcon = @"com.haidian.remote:drawable/icon_template_air_condition";
    }else if (type == DEVICE_STB) {//机顶盒
        deviceIcon = @"com.haidian.remote:drawable/icon_template_stb";
    }else if (type == DEVICE_SOUND) {//音响
        deviceIcon = @"com.haidian.remote:drawable/icon_template_music";
    }else if (type == DEVICE_CUSTOM) {//自定义
        deviceIcon = @"com.haidian.remote:drawable/icon_template_edit";
    }else if (type == DEVICE_XIAOMI) {//小米盒子
        deviceIcon = @"com.haidian.remote:drawable/icon_template_xioami_box";
    }else if (type == DEVICE_APPLETV) {//appletv
        deviceIcon = @"com.haidian.remote:drawable/icon_template_itv";
    }else if (type == DEVICE_SOCKET1) {//插座1
        deviceIcon = @"com.haidian.remote:drawable/icon_template_rf_one_key";
    }else if (type == DEVICE_SOCKET2) {//插座2
        deviceIcon = @"com.haidian.remote:drawable/icon_template_rf_two_key";
    }else if (type == DEVICE_SOCKET3) {//插座3
        deviceIcon = @"com.haidian.remote:drawable/icon_template_rf_three_key";
    }
    return deviceIcon;
}
-(NSString*)enumToString:(DEVICE_TYPE)type{
    NSString *devicetype = nil;
    if (type == DEVICE_TV) {//电视
        devicetype = @"TV";
    }else if (type == DEVICE_AIR) {//空调
        devicetype = @"AIR_CONDITION";
    }else if (type == DEVICE_STB) {//机顶盒
        devicetype = @"STB";
    }else if (type == DEVICE_SOUND) {//音响
        devicetype = @"MUSIC";
    }else if (type == DEVICE_CUSTOM) {//自定义
        devicetype = @"COTSTOM";
    }else if (type == DEVICE_XIAOMI) {//小米盒子
        devicetype = @"XIAO_MI_BOX";
    }else if (type == DEVICE_APPLETV) {//appletv
        devicetype = @"ITV";
    }else if (type == DEVICE_SOCKET1) {//插座1
        devicetype = @"RF_ONE_KEY";
    }else if (type == DEVICE_SOCKET2) {//插座2
        devicetype = @"RF_TWO_KEY";
    }else if (type == DEVICE_SOCKET3) {//插座3
        devicetype = @"RF_THREE_KEY";
    }
    return devicetype;
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"Client Disconnected: %@:%hu", [sock connectedHost], [sock connectedPort]);
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
	[connectedSockets removeObject:sock];
}

-(void)sendUdpData{
    if (!self.udpSocket) {
        self.udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
        
        NSError *error = nil;
        [self.udpSocket enableBroadcast:YES error:&error];
        if (![self.udpSocket bindToPort:m_port error:&error]){
            NSLog(@"bindToPort error");
        }
        [self startServer];
        
//        [[PokerControlClient share] startServer:import_port];
    }
    [self.udpSocket receiveWithTimeout:-1 tag:0];
    NSString *sentip = @"255.255.255.255";
    NSString *dataStr = @"IMPORT_PROBE_iPhone";
    NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"SEND TO : %@:%d    %@", sentip, m_port, dataStr);
    [self.udpSocket sendData:data toHost:sentip port:m_port withTimeout:-1 tag:0];
    if (!isStopUdpSend) {
       [self performSelector:@selector(sendUdpData) withObject:nil afterDelay:1];
    }
}
@end




